package cn.virens.util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import cn.virens.exception.APIException;

public class ObjectUtil {
	public static Map<String, Object> toMap(Object obj, String err) {
		if (obj == null) { throw new APIException("Null", err); }

		Map<String, Object> answer = new HashMap<>();

		Class<?> clazz = obj.getClass();
		for (Field field : clazz.getDeclaredFields()) {
			// 如果不是普通字段就跳过
			if ((field.getModifiers() & 0xff8) != 0) {
				continue;
			}

			try {
				String feildName = field.getName();

				PropertyDescriptor propertyDescriptor = new PropertyDescriptor(feildName, clazz);
				Method method = propertyDescriptor.getReadMethod();
				// 如果没有找到该该字段的度方法就跳过
				if (method == null) {
					continue;
				}

				// 读取该字段的值
				answer.put(feildName, method.invoke(obj));
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IntrospectionException e) {
				e.printStackTrace();
			}
		}

		return answer;
	}
}
